/**
 * 订单详情页面逻辑
 * 处理订单详情展示、订单状态变更等功能
 */

// 全局变量
let currentOrder = null;

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    initAuthState();
    loadOrderDetails();
    setupEventListeners();
});

// 初始化用户认证状态
function initAuthState() {
    const user = JSON.parse(localStorage.getItem('user'));
    if (user) {
        document.getElementById('auth-text').textContent = user.username;
    } else {
        // 未登录用户跳转到登录页
        window.location.href = 'login.html';
    }
}

// 设置事件监听器
function setupEventListeners() {
    // 可以根据订单状态动态添加按钮事件
}

// 加载订单详情
async function loadOrderDetails() {
    try {
        // 从URL获取订单ID
        const urlParams = new URLSearchParams(window.location.search);
        const orderId = urlParams.get('id');

        if (!orderId) {
            throw new Error('缺少订单ID参数');
        }

        // 显示加载状态
        document.getElementById('order-id').textContent = `#${orderId}`;

        // 获取订单详情
        const response = await api.orders.get(orderId);
        currentOrder = response.data;

        // 渲染订单详情
        renderOrderDetails();

    } catch (error) {
        console.error('加载订单详情失败:', error);
        document.getElementById('order-status').textContent = '加载订单详情失败';
    }
}

// 渲染订单详情
function renderOrderDetails() {
    if (!currentOrder) return;

    // 基本信息
    document.getElementById('order-number').textContent = currentOrder.orderNumber;
    document.getElementById('create-time').textContent = formatTime(currentOrder.createTime);
    document.getElementById('pay-time').textContent = currentOrder.payTime ? formatTime(currentOrder.payTime) : '-';
    document.getElementById('total-amount').textContent = `¥${currentOrder.totalAmount.toFixed(2)}`;
    document.getElementById('payment-method').textContent = getPaymentMethodText(currentOrder.paymentMethod);

    // 订单状态
    const statusElement = document.getElementById('order-status');
    statusElement.textContent = getOrderStatusText(currentOrder.status);
    statusElement.className = `order-status ${currentOrder.status.toLowerCase()}`;

    // 渲染订单商品
    renderOrderItems();

    // 渲染订单操作按钮
    renderOrderActions();
}

// 渲染订单商品
function renderOrderItems() {
    const itemsList = document.getElementById('items-list');
    itemsList.innerHTML = '';

    if (!currentOrder.items || currentOrder.items.length === 0) {
        itemsList.innerHTML = '<div class="no-items">暂无商品</div>';
        return;
    }

    currentOrder.items.forEach(item => {
        const itemElement = document.createElement('div');
        itemElement.className = 'order-item';
        itemElement.innerHTML = `
            <div class="item-image">
                <img src="${item.product.mainImage || 'images/default-product.png'}" alt="${item.product.name}">
            </div>
            <div class="item-info">
                <h4 class="item-name">${item.product.name}</h4>
                <div class="item-price">¥${item.price.toFixed(2)}</div>
                <div class="item-quantity">×${item.quantity}</div>
                <div class="item-total">小计: ¥${(item.price * item.quantity).toFixed(2)}</div>
            </div>
        `;
        itemsList.appendChild(itemElement);
    });
}

// 渲染订单操作按钮
function renderOrderActions() {
    const actionsContainer = document.getElementById('order-actions');
    actionsContainer.innerHTML = '';

    // 根据订单状态显示不同按钮
    switch (currentOrder.status) {
        case 'UNPAID':
            actionsContainer.innerHTML = `
                <button class="btn btn-pay" id="pay-btn">立即支付</button>
                <button class="btn btn-cancel" id="cancel-btn">取消订单</button>
            `;
            document.getElementById('pay-btn').addEventListener('click', payOrder);
            document.getElementById('cancel-btn').addEventListener('click', cancelOrder);
            break;

        case 'PAID':
            actionsContainer.innerHTML = `
                <button class="btn btn-confirm" id="confirm-btn">确认收货</button>
            `;
            document.getElementById('confirm-btn').addEventListener('click', confirmReceipt);
            break;

        case 'SHIPPED':
            actionsContainer.innerHTML = `
                <button class="btn btn-confirm" id="confirm-btn">确认收货</button>
            `;
            document.getElementById('confirm-btn').addEventListener('click', confirmReceipt);
            break;

        case 'COMPLETED':
            if (!currentOrder.reviewed) {
                actionsContainer.innerHTML = `
                    <button class="btn btn-review" id="review-btn">评价商品</button>
                `;
                document.getElementById('review-btn').addEventListener('click', reviewProducts);
            }
            break;

        case 'CANCELLED':
            // 已取消订单无操作按钮
            break;
    }
}

// 支付订单
async function payOrder() {
    try {
        // 这里应该是调用支付接口的逻辑
        // 模拟支付成功
        await api.orders.update({ id: currentOrder.id, status: 'PAID' });

        alert('支付成功');
        // 重新加载订单详情
        await loadOrderDetails();
    } catch (error) {
        console.error('支付失败:', error);
        alert('支付失败: ' + (error.message || '请重试'));
    }
}

// 取消订单
async function cancelOrder() {
    try {
        if (!confirm('确定要取消此订单吗？')) return;

        await api.orders.cancel(currentOrder.id);
        alert('订单已取消');
        // 重新加载订单详情
        await loadOrderDetails();
    } catch (error) {
        console.error('取消订单失败:', error);
        alert('取消订单失败: ' + (error.message || '请重试'));
    }
}

// 确认收货
async function confirmReceipt() {
    try {
        if (!confirm('确认已收到商品吗？')) return;

        await api.orders.update({ id: currentOrder.id, status: 'COMPLETED' });
        alert('确认收货成功');
        // 重新加载订单详情
        await loadOrderDetails();
    } catch (error) {
        console.error('确认收货失败:', error);
        alert('确认收货失败: ' + (error.message || '请重试'));
    }
}

// 评价商品
function reviewProducts() {
    // 跳转到评价页面
    window.location.href = `review.html?orderId=${currentOrder.id}`;
}

// 辅助函数：获取订单状态文本
function getOrderStatusText(status) {
    const statusMap = {
        'UNPAID': '待支付',
        'PAID': '已支付',
        'SHIPPED': '已发货',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
    };
    return statusMap[status] || status;
}

// 辅助函数：获取支付方式文本
function getPaymentMethodText(method) {
    const methodMap = {
        'ALIPAY': '支付宝',
        'WECHAT': '微信支付',
        'BANK': '银行卡',
        'CASH': '现金'
    };
    return methodMap[method] || method;
}

// 辅助函数：格式化时间
function formatTime(timestamp) {
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
}

// 辅助函数：补零
function padZero(num) {
    return num < 10 ? `0${num}` : num;
}